﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using PickEmHats;
using MySql.Data.MySqlClient;

namespace PickEmHats
{
    public class TeamFactory : HatsFactoryBase
    {

        public TeamFactory(string connString)
        {
            ConnString = connString;
        }

        public List<Team> GetTeamData()
        {
            InstantiateDBConnection();

            List<Team> list = new List<Team>();
            sqlCmd.CommandText = @"SELECT * FROM hats.team;";

            using (sqlConn)
            {
                try
                {
                    sqlConn.Open();
                    sqlRdr = sqlCmd.ExecuteReader();
                    while (sqlRdr.Read())
                    {
                        list.Add(GetFromRdr());
                    }
                }
                catch (MySqlException e)
                {
                    throw (e);
                }
            }
            //finally
            //{
            //    conn.Dispose();
            //}

            return list;
        }

        public void AddTeam(Team t)
        {
            InstantiateDBConnection();
            sqlCmd.Parameters.AddWithValue("?name", t.Name);
            sqlCmd.Parameters.AddWithValue("?city", t.City);
            sqlCmd.Parameters.AddWithValue("?abbr", t.Abbreviation);

            sqlCmd.CommandText = @"INSERT INTO hats.team (name, city, abbreviation) 
                                   VALUES(?name,?city,?abbr);";

            using (sqlConn)
            {
                try
                {
                    sqlConn.Open();
                    sqlCmd.ExecuteNonQuery();
                }
                catch (MySqlException e)
                {
                    throw e;
                }

            }



        }

        private Team GetFromRdr()
        {
            return new Team(Convert.ToInt32(sqlRdr["id"]),
                            sqlRdr["name"].ToString(),
                            sqlRdr["city"].ToString(),
                            sqlRdr["abbreviation"].ToString());
        }
    }
}